//
//  ShmApiTool.swift
//  PianoKeyboardMaster
//
//  Created by ins-yangming on 2023/3/6.
//

import UIKit
import SwiftyJSON



class ShmApiTool: NSObject, URLSessionDelegate {
    
    
    
    @objc static let shareInstance: ShmApiTool = {
        let instance = ShmApiTool();
        return instance
    }()
    
    override init() {
        super.init();
    }
    
    
    
    override func setValue(_ value: Any?, forKey key: String) {
        super.setValue(value, forKey: key);
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        //        print("UndefinedKey " + key);
    }
    
    
    
    func ServerUrl() -> String {
        //#if DEBUG // 判断是否在测试环境下
        return "http://inscloud.192.168.0.226.nip.io";
        //#else
        //        return "https://dtinscloud.dnfie.com";
        //#endif
    }
    
    
    // MARK: - 获取所有的分类
    func searchMusic(callback : ShmSimplePassByValue?){
        if let url = URL(string: "\(ServerUrl())/psm/test/getCcPage?no=1&size=1") {
            self.getInfoFromServer(url: url, headDict: [:], bodyData: nil, method: "GET") { infoData in
                if let currentInfoDict = JSON(infoData).dictionary {
                    
                    if currentInfoDict["code"]?.intValue == 0 {
                        //拿到用户信息
                        if let data = currentInfoDict["data"]?.dictionary?["records"]?.array?.first {
                            let model = ShmCxMusicModel(songId: data["id"].stringValue, songName: data["name"].stringValue, songUrl: data["playJson"].stringValue);
                            DispatchQueue.main.async {
                                callback?(model);
                            }
                            return;
                        }
                    }
                }
                DispatchQueue.main.async {
                    callback?(false);
                }
            }
        }
    }
    
    // MARK: - 获取分类下面的歌曲
    func getCategorieMusics(musicId : String, xmlString : String , callback : ShmSimplePassByValue?){
        let string = "\(ServerUrl())/psm/test/uploadCCXml";
        let bodyDict = ["id" : musicId, "xml" : xmlString];
        guard let bodyData = JSON(bodyDict).rawString()?.data(using: .utf8) else {
            callback?(false);
            return;
        }
        let headDict: [String : String] = [
            "Content-Type": "application/json"
        ]
        if let url = URL(string: string) {
            self.getInfoFromServer(url: url, headDict: headDict, bodyData: bodyData, method: "post") { infoData in
                if let currentInfoDict = JSON(infoData).dictionary {
                    
                    if currentInfoDict["code"]?.intValue == 0 {
                        DispatchQueue.main.async {
                            callback?(true);
                        }
                    }else {
                        //                        DispatchQueue.main.async {
                        //                            callback?(false);
                        //                        }
                        self.skipMusics(musicId: musicId, callback: callback);
                        print(currentInfoDict["msg"]);
                    }
                }else{
                    DispatchQueue.main.async {
                        callback?(false);
                    }
                }
            }
        }
    }
    
    
    // MARK: - 获取分类下面的歌曲
    func skipMusics(musicId : String, callback : ShmSimplePassByValue?){
        let string = "\(ServerUrl())/psm/test/ccw/skip";
        let bodyDict = ["id" : musicId];
        guard let bodyData = JSON(bodyDict).rawString()?.data(using: .utf8) else {
            callback?(false);
            return;
        }
        let headDict: [String : String] = [
            "Content-Type": "application/json"
        ]
        if let url = URL(string: string) {
            self.getInfoFromServer(url: url, headDict: headDict, bodyData: bodyData, method: "post") { infoData in
                if let currentInfoDict = JSON(infoData).dictionary {
                    
                    if currentInfoDict["code"]?.intValue == 0 {
                        DispatchQueue.main.async {
                            callback?(true);
                        }
                    }else {
                        DispatchQueue.main.async {
                            callback?(false);
                        }
                        print(currentInfoDict["msg"]);
                    }
                }else{
                    DispatchQueue.main.async {
                        callback?(false);
                    }
                }
            }
        }
    }
    
    
    
    // MARK: - 服务器请求方法
    func getInfoFromServer(url: URL, headDict: [String : String], bodyData: Data?, method: String, dataBack: ShmSimplePassByValue?) {
        var request =  URLRequest(url: url);
        if bodyData != nil {
            request.httpBody = bodyData;
        }
        request.httpMethod = method;
        request.timeoutInterval = 10;
        for key in headDict.keys {
            request.setValue(headDict[key], forHTTPHeaderField: key);
        }
        let session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue());
        let task = session.dataTask(with: request) { (data, respone, error) in
            if error != nil {
                debugPrint("请求失败1  \(error.debugDescription)");
                dataBack?(false);
                return;
            }
            guard let infoData = data else {
                dataBack?(false);
                return;
            }
            //回调
            dataBack?(infoData);
        }
        task.resume();
    }
    
    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        guard let serverTrust = challenge.protectionSpace.serverTrust else {
            return completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
        }
        return completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
    }
    
}
